package com.cms.recursoshumanos.activity.user.poliza.carta_aval;

import com.example.frontendrecursoshumanos.R;
import com.cms.recursoshumanos.activity.main.MainRecursosHumanosActivity;
import com.cms.recursoshumanos.cache.UserInfoCache;
import com.cms.recursoshumanos.handler.DetailPolizaActivityHandler;
import com.cms.recursoshumanos.object.Empleado;
import com.cms.recursoshumanos.object.Poliza;
import com.cms.recursoshumanos.object.Usuario;
import com.cms.recursoshumanos.object.list.ListaFamiliar;
import com.cms.recursoshumanos.utilities.Tool;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ProgressDialog;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

public class SetCartaAvalActivity extends MainRecursosHumanosActivity 
{

	
	private Spinner spinnerPaciente;
	private Spinner spinnerHospital;
	private EditText textOperacion;
	private EditText textMonto;
	private static Empleado elEmpleado;
	private static Poliza laPoliza;
	private static ListaFamiliar listado_familiar;
	private Usuario elUsuario;
	private ProgressDialog dialog;
	
	private SetCartaAvalAsync asyncSetCartaAvalTask;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_set_carta_aval);
		setupUI(findViewById(R.id.parent_layout));
		elUsuario = UserInfoCache.getInstance().getUsuario();
		elEmpleado = UserInfoCache.getInstance().getEmpleado();
		laPoliza = UserInfoCache.getInstance().getPoliza();
		listado_familiar = UserInfoCache.getInstance().getListaFamiliar();
		setComponents();
		
	}
	@Override
	protected void onResume() 
	{
		super.onResume();
		if (elUsuario == null)
		{
			elUsuario = UserInfoCache.getInstance().getUsuario();
		}
		if (elEmpleado == null)
		{
			elEmpleado = UserInfoCache.getInstance().getEmpleado();
		}
		if (laPoliza == null)
		{
			laPoliza = UserInfoCache.getInstance().getPoliza();
		}
		if (listado_familiar == null)
		{
			listado_familiar = UserInfoCache.getInstance().getListaFamiliar();
		}
		
		
	}

	
	public void setComponents()
	{
		LinearLayout layout_info_general = (LinearLayout) findViewById(R.id.llInformacionGeneralSetCartaAVal);
		
		spinnerPaciente = (Spinner) layout_info_general.findViewById(R.id.spValueBeneficiario);
		spinnerHospital = (Spinner) layout_info_general.findViewById(R.id.spValueHospital);
		TextView textViewPoliza = (TextView) layout_info_general.findViewById(R.id.tvValuePoliza);
		TextView textViewTitular = (TextView) layout_info_general.findViewById(R.id.tvValueTitular);
		textOperacion = (EditText) layout_info_general.findViewById(R.id.etValueOperacion);
		textMonto = (EditText) layout_info_general.findViewById(R.id.etValueMonto);
		
		textMonto.setOnFocusChangeListener(new OnFocusChangeListener() 
		{
			
			@Override
			public void onFocusChange(View v, boolean hasFocus) 
			{
				try
				{
					if (hasFocus)
					{
						if (Integer.parseInt(textMonto.getText().toString()) == 0 )
						{
							textMonto.setText("");
						}
					}
					else
					{

						if ((textMonto.getText() == null) || ( Integer.parseInt(textMonto.getText().toString()) == 0) )
						{
							textMonto.setText("0");
						}
					}
				}
				catch (Exception e)
				{
					if (hasFocus)
					{
						textMonto.setText("");
					}
					else
					{
						textMonto.setText("0");
					}
				}
				
			}
		});

		ArrayAdapter <String> adapter_hospitales = new ArrayAdapter <String>(this,
		        android.R.layout.simple_spinner_item, 
		        laPoliza.getSeguro().getListadoHospital().getListaHospitalForSpinner());
		ArrayAdapter <String> adapter_familiar = new ArrayAdapter <String>(this,
		        android.R.layout.simple_spinner_item, 
		        listado_familiar.getListaFamiliarForSpinner());
		
		spinnerHospital.setAdapter(adapter_hospitales);
		spinnerPaciente.setAdapter(adapter_familiar);
		
		textViewPoliza.setText(""+laPoliza.getNumeroPoliza());
		textViewTitular.setText(elEmpleado.getPersona().getApellido_Persona_1()+", "+
								elEmpleado.getPersona().getNombre_Persona_1());

				
		
	}
	public static void hideSoftKeyboard(MainRecursosHumanosActivity activity) 
	{
	    InputMethodManager inputMethodManager = (InputMethodManager)  activity.getSystemService(MainRecursosHumanosActivity.INPUT_METHOD_SERVICE);
	    inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
	}
	public void setupUI(View view) 
	{

	    //Set up touch listener for non-text box views to hide keyboard.
	    if(!(view instanceof EditText))
	    {

	    	view.setOnTouchListener(new OnTouchListener() 
	    	{
	    		
	    		@Override
	            public boolean onTouch(View v, MotionEvent event) 
	    		{
	                hideSoftKeyboard(SetCartaAvalActivity.this);
	                return false;
	            }
	        });
	        
	        if (view instanceof android.view.ViewGroup) 
	        {
	            for (int i = 0; i < ((android.view.ViewGroup) view).getChildCount(); i++) 
	            {
	                View innerView = ((android.view.ViewGroup) view).getChildAt(i);

	                setupUI(innerView);
	            }
	        }
	    }
	}
	
	public void onEnviarSolicitudClick(View v)
	{
		asyncSetCartaAvalTask = new SetCartaAvalAsync(elUsuario);
		asyncSetCartaAvalTask.execute();
	}
	
	
	private class SetCartaAvalAsync extends AsyncTask<String, Void, String>
	{

		private Usuario elUsuario;
		

		public  SetCartaAvalAsync(Usuario elUsuario)
	    {
			this.elUsuario = elUsuario;
	    }
		@SuppressWarnings("deprecation")
		@Override
		protected void onPreExecute()
		{
			showDialog(0);
			dialog = ProgressDialog.show(SetCartaAvalActivity.this, "Espere","Procesando la Solicitud...",true );
		}
	
		@Override
		protected String doInBackground(String... arg0) 
		{
			DetailPolizaActivityHandler handler = new DetailPolizaActivityHandler();
			String result = handler.getPlanillaCartaAval(this.elUsuario.getNombre_Usuario(),
															this.elUsuario.getPassword(),
															laPoliza,
															textOperacion.getText().toString(),
															textMonto.getText().toString(),
															laPoliza.getSeguro().
																getListadoHospital().
																getHospitalAtIndex(spinnerHospital.getSelectedItemPosition()),
															listado_familiar.getListaFamiliarAsegurado().
																getFamiliarAtIndex(spinnerPaciente.getSelectedItemPosition()));
														
			return result;
		}
		
		@Override
		public void onPostExecute(String  result)
		{
			
			String str_result = result;
			
			Tool.getInstance().showMessagePlanillas(str_result);
			
			dialog.cancel();
			this.cancel(true);
		}
	}
}
